package org.yxj.lib_downfile.down;

import org.yxj.lib_downfile.i.DownFileProgressListener;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;


/**
 * @author on 2022/8/25
 */
public class ProgressResponseBody extends ResponseBody {

    private DownFileProgressListener DownFileProgressListener;
    private final ResponseBody responseBody;
    private BufferedSource bufferedSource;


    public ProgressResponseBody(ResponseBody responseBody,DownFileProgressListener DownFileProgressListener) {
        this.responseBody = responseBody;
        this.DownFileProgressListener=DownFileProgressListener;
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }


    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }



    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;
                DownFileProgressListener.onProgress(null,totalBytesRead,responseBody.contentLength());
                return bytesRead;
            }
        };
    }
}
